import { BaseURL } from '../../app.js';

const util = require('../../utils/util.js')

let playTimeInterval
let recordTimeInterval
const recorderManager = wx.getRecorderManager();

const options = {
  duration: 60000,
  sampleRate: 16000,
  numberOfChannels: 1,
  encodeBitRate: 48000,
  format: 'mp3'
  // frameSize: 50
}

Page({
  onShareAppMessage() {
    return {
      title: '录音',
      path: '../voice/voice'
    }
  },

  data: {
    uid: '',
    phone: '',
    step: 1,
    // res:'',
    numberToRead: '',
    sessionId: '',
    tempFilePath: '',
    recording: false,
    playing: false,
    hasRecord: false,
    recordTime: 0,
    playTime: 0,
    formatedRecordTime: '00:00:00',
    formatedPlayTime: '00:00:00'
  },

  onLoad: function(options) {

    recorderManager.onStart(() => {
      console.log('recorder start')
    })

    recorderManager.onPause(() => {
      console.log('recorder pause')
    })

    recorderManager.onStop((res) => {
      console.log('recorder stop', res)
      const { tempFilePath } = res
      console.log('recorderManager.onStop() tempFilePath:' + tempFilePath)

      const that = this;
      this.data.tempFilePath = tempFilePath
      that.upload();

    })

    recorderManager.onError((res) => {

      console.log(res);

    })

    recorderManager.onFrameRecorded((res) => {
      const { frameBuffer } = res
      console.log('frameBuffer.byteLength', frameBuffer.byteLength)
    })

    // this.setData({
    //   uid: options.phone
    // }) 

    this.data.phone = wx.getStorageSync('phone');
    var tempStep = wx.getStorageSync('step');

    if (tempStep) {
      this.setData({
        phone: this.data.phone,
        step: tempStep
      })
    } else {
      this.setData({
        phone: this.data.phone
      })
    }

    // var that = this;
    // wx.request({
    //   url: 'https://aqhy.citydo.com.cn/safe/mini/getToken',

    //   method: 'POST',

    //   success: function (res) {

    //     if (res.data.code == 0) {

    //       var data = res.data
    //       var code = res.data.code
    //       var numberToRead = res.data.data.token
    //       var sessionId = res.data.data.sessionId

    //       that.setData({
    //         numberToRead: res.data.data.token,
    //         sessionId: res.data.data.sessionId
    //       })

    //     } else {

    //       wx.showModal({
    //         title: '提示',
    //         content: res.data.msg
    //       })


    //     }

    //     // res = JSON.parse(res.data)
    //   },
    //   fail: function (res) {
    //     console.log(res);
    //   }
    // })

  },

  onShow (){

  },


  onHide() {

    if (this.data.playing) {
      recorderManager.stop();
    }

  },

  startRecord() {


    recorderManager.start(options)

    this.setData({
      recording: true
    })

    const that = this
    recordTimeInterval = setInterval(function() {
      const recordTime = that.data.recordTime += 1
      that.setData({
        formatedRecordTime: util.formatTime(that.data.recordTime),

        recordTime
      })
    }, 1000)

  },

  stopRecord() {
    // wx.stopRecord()
    const that = this

        that.setData({
          recording: false,
          formatedRecordTime: '00:00:00'

        })
    clearInterval(recordTimeInterval)
    recorderManager.stop();

  },

  userNameInput(e) {
    this.setData({
      phone: e.detail.value
    })
  },

  upload(res) {

    wx.showLoading({
      title: '录音上传中',
    })

    var tempFilePath = this.data.tempFilePath;
    var phone = this.data.phone;

    wx.uploadFile({

      // url: "http://172.16.16.110:8180/safe/mini/singleVoiceVerify",
      url: 'http://172.16.16.77:8180/menjin/test/miniProgramFaceRegister',
      filePath: tempFilePath,
      name: "file",
      method: 'POST',
      header: {

        'Content-Type': 'multipart/form-data'
        // ,
        // APIKEY: authData["APIKEY"],
        // timestamp: authData["timestamp"],
        // nonce: authData["nonce"],
        // signature: authData["signature"],
        // APISECRET: authData["api_secret"]
      },
      formData: {
        phone: phone
      },
      success: function(res) {
        wx.hideLoading();
        var data = res.data
        res = JSON.parse(res.data)
        if(res.code == 0){
 
          console.info(res.msg)
          wx.showModal({
            title: '提示',
            content: res.msg,
            success: function (res) {
              wx.redirectTo({
                url: '../index/index'
              })
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: res.msg,
            showCancel: false,
            success: function (res) {

              wx.redirectTo({
                url: '../index/index'
              })
            }
          })
        }
      },

      fail: function() {
        wx.showModal({
          title: '提示',
          content: '网络失败',
          showCancel: false,
          success: function (res) {

            wx.redirectTo({
              url: '../index/index'
            })
            
          }
        })
      }
      // ,
      // complete: () => {
      //   wx.showModal({
      //     title: '提示',
      //     content: '音频上传完成'
      //   })

      // }

    })
  }
})